import { MainApi } from "./MainApi";
import axios, { AxiosError } from "axios";
import { message } from "ant-design-vue";
import { OpenAPI } from "@/api/core/OpenAPI";
import { useUserStore } from "@/stores/useUser";
import { useTabsStore } from "@/stores/tabs";
import router from "@/router";

const Client = new MainApi({
  BASE: "http://127.0.0.1:8080",
});

// Add a request interceptor
axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    const userStore = useUserStore();
    if (userStore.token && userStore.token != "") {
      // @ts-ignore
      config.headers.set("zshop", userStore.token);
    }
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
axios.interceptors.response.use(
  function (response) {
    // 任何位于2xx范围内的状态代码都会触发此函数
    // 对响应数据执行操作

    return response;
  },
  function (error: AxiosError<string>) {
    // 任何超出2xx范围的状态代码都会触发此功能
    // 处理响应错误
    if (error.response?.status == 401) {
      message.error("请先登录");
      // 清除用户信息
      const userStore = useUserStore();
      userStore.clearInfo();
      // 清除tabs
      const tabsStore = useTabsStore();
      tabsStore.clearTabs();
      router.push("/login");
      return;
    }
    message.error(error.response?.data ?? "请求异常");
    return Promise.reject(error);
  }
);

export { Client };
